package com.pathfinder.model;

import com.pathfinder.utils.Log;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

/**
 * Date: 09.05.11
 *
 * @author Victor Passichenko (vpas@yandex-team.ru)
 */
public class Serialization {
    public static String toJSON(Game game) {
        try {
            return new JSONStringer().
                    object().
                        key("name").value(game.getName()).
                    endObject()
            .toString();
        } catch (JSONException e) {
            Log.error("error in toJSON(game)", e);
            return null;
        }
    }

    public static String toJSON(PlayerInfo playerInfo) {
        try {
            return new JSONStringer().
                    object().
                        key("name").value(playerInfo.getName()).
                        key("role").value(playerInfo.getRole().toString().toLowerCase()).
                        key("color").value(playerInfo.getColorName()).
                    endObject()
            .toString();
        } catch (JSONException e) {
            Log.error("error in toJSON(playerInfo)", e);
            return null;
        }
    }

    public static Game gameFromJson(JSONObject jsonGame) throws JSONException {
        int id = jsonGame.getInt("id");
        String name = jsonGame.getString("name");
        return new Game(id, name);
    }
}
